const { CSV_PATH, BUNDLE_DIR, TEMPLATE_DIR, REPO_DIR } = require("../constant");
const MatrixProduct = require("../utils/csv");
const fs = require('fs');
const path = require('path');
const { Worker } = require('worker_threads');
const shelljs = require('shelljs');
const Default_Xml = require("../utils/xml");
const { DEFAULT_XML } = require("../constant/index")
const os = require('os');

async function downloadProduct() {
    const [
        codeBranch = "OpenHarmony-3.0-LTS",
        version = "3.1.0",
        loginUser = "8EBENJ2",
        productName = "bes2600"
    ] = process.argv.slice(2)
    // shelljs.rm("-rf", path.resolve(REPO_DIR, "*"), { async: true })
    const matrixProduct = MatrixProduct.fromPath(CSV_PATH)
    const repoNames = matrixProduct.matchedRepos(productName)
    const default_xml = await Default_Xml.fromPath(DEFAULT_XML)
    let workerCount = 0
    const errlogs = []
    repoNames.forEach(repoName => {
        const worker = new Worker(path.resolve(__dirname, "..", "thread", "index.js"), {
            workerData: {
                repoName,
                version,
                action: "pack",
                destPath: default_xml.matchRepo(repoName),
                codeBranch
            }
        })
        worker.on("exit", async exitCode => {
            workerCount++
            if (workerCount === repoNames.length) {
                console.log(errlogs.join(os.EOL));
                const distrubtionCWD = path.resolve(TEMPLATE_DIR, productName)
                await traverseDownload(distrubtionCWD)
            }
            if (exitCode === -1) {
            }
        })
        worker.on("message", log => {
            errlogs.push(log)
        })
    })
}

async function traverseDownload(cwd) {
    const installTgzs = fs.readdirSync(BUNDLE_DIR, { encoding: 'utf-8' })
    for (const tgzName of installTgzs) {
        const tgzPath = path.resolve(BUNDLE_DIR, tgzName)
        await localInstall(tgzPath, cwd)
    }
    await shelljs.exec(`hpm code restore`, { async: true, cwd })
}

function getTgzName(repoName) {
    const pkgName = repoName
        .toLowerCase()
        .replace("third_party_", "")
        .replaceAll("-", "_")
    return `@ohos-${pkgName}-version.tgz`
}

function localInstall(tgzPath, cwd) {
    return new Promise((resolve, reject) => {
        const child = shelljs.exec(`hpm install ${tgzPath}`, { async: true, cwd, silent: true })
        child.stdout.on("close", () => {
            resolve()
        })
        child.stdout.on("error", () => {
            reject()
        })
    })
}


downloadProduct()